/*
*******************************************************************************
* 列表常规动作工具集(需要Hongs-CORE-js的支持)
*
* Author: Huang Hong
* Support: kevin.hongs@gmail.com, +8613718308220
*
* Usage:

var LA = new HsListAction("listId", true);
// 设置动作URL
LA.getAction = "/xxx/info.act";
LA.setAction = "/xxx/form.act";
LA.delAction = "/xxx/delete.act";

*
* Funcs:

LA.get(id);               // 查看
LA.set(id);               // 编辑
LA.del(id);               // 删除一行
LA.del();                 // 删除全部
LA.checkRow(id, checked); // 选中一行
LA.checkAll(checked);     // 选中全部

*
* Event:

LA.onGet();   // 查看确认, 返回true阻止默认行为
LA.onSet();   // 编辑确认, 同上
LA.onDel();   // 删除确认, 同上
LA.onDel2();  // 删除二次确认, 同上
LA.onBack();  // 成功后执行, 同上
LA.onFail();  // 失败后执行

*
* Style:

.list_hover // 悬浮高亮样式
.list_light // 行高亮样式

*******************************************************************************
*/

function HsListAction (listObj, useFW) {
  var _this = this;

  _this.listObj = listObj; // 列表对象(TABLE)
  _this.useLE = listObj ? true : false;
  _this.useFW = useFW ? true : false;

  _this.getAction = "";   // 查看页URL
  _this.setAction = "";   // 编辑页URL
  _this.delAction = "";   // 删除页URL
  _this.idVar = "id";     // ID参数
  _this.idsVar = "ids[]"; // IDs名称
  _this.findVar = "find"; // 搜索参数
  _this.pageVar = "page"; // 分页参数

  _this.noTitle = false; // 无悬浮显示
  _this.noClick = false; // 无点击动作
  _this.lightClass = self.listLightClass; // 行高亮样式类
  _this.hoverClass = self.listHoverClass; // 悬浮高亮样式类

  _this.noDelConfirm = false; // 无删除确认
  _this.delConfirmMsg = self.delConfirmMsg; // 删除确认消息
  _this.delNoCheckedMsg = self.delNoCheckedMsg; // 删除未选择消息

  _this.openType = 0; // 浮动窗开启方式
  _this.openParams = []; // 浮动窗参数
  _this.checkBoxes = []; // 复选框集合
  _this.actionType = ''; // 当前操作类型

  _this.W   = null;
  _this.FW  = null;
  _this.FA  = null;

  _this.init = function() {
    if (!_this.listObj) {
      return;
    }

    if (!_this.useLE) {
      return;
    }

    if (typeof _this.listObj == "string") {
      _this.listObj = hsId(_this.listObj);
    }

    if (!_this.listObj) {
      hsError(self.listActionNoTableErr, "HsListEvent");
      return;
    }

    _this.initEvent();
  };

  /** 列表常规动作 **/

  _this.get = function(id) {
    if (_this.onGet(id)) {
      return false;
    }

    _this.actionOpen(_this.getAction, id);
    return false;
  };

  _this.set = function(id) {
    if (_this.onSet(id)) {
      return false;
    }

    if (id) {
      _this.actionType = "set";
    }
    else {
      _this.actionType = "add";
    }

    _this.actionOpen(_this.setAction, id);
    return false;
  };

  _this.del = function(id) {
    if (_this.onDel(id)) {
      return false;
    }

    var send = [];
    if (id) {
      send.push({name:_this.idsVar,value:id});
    }
    else {
      var a = hsName(_this.idsVar);
      for (var i = 0; i < a.length; i ++) {
        if (a[i].checked) {
          send.push({name:_this.idsVar,value:a[i].value});
        }
      }
      if (send.length == 0) {
        alert(_this.delNoCheckedMsg);
        return false;
      }
    }

    if (!_this.noDelConfirm && !confirm(_this.delConfirmMsg)) {
      return false;
    }

    if (_this.onDel2(id)) {
      return false;
    }
    _this.actionType = "del";

    this.actionSubmit(_this.delAction, send);
    return false;
  };

  _this.find = function(text, vars) {
    var url = location.href;

    if (typeof text == "object" && text != null) {
      var ev = hsGetStandardEvent(text);
      url = hsUrlBindParams(url, ev.target.elements);
    }
    else {
      url = hsUrlBindParam(url, find, text);
    }
    if (vars) {
      url = hsUrlBindParams(url, vars);
    }
    url = hsUrlBindParam(url, page, null);
    location.href = url;
  };

  /** 常规动作工具函数 **/

  _this.getWindow = function() {
    if (!_this.W) {
      _this.setWindow();
    }
    return _this.W;
  };

  _this.setWindow = function(w) {
    if (!w) {
      w = window;
    }
    _this.W = w;
  };

  _this.getFW = function() {
    if (!_this.FW) {
      _this.setFW();
    }
    return _this.FW;
  };

  _this.setFW = function(fw) {
    if (!fw) {
      var w = _this.getWindow();
      var fw = new w.HsFloatWindowCreator(0, 0, "normal");
      fw.setOpenerWindow(self);
    }
    _this.FW = fw;
  };

  _this.actionOpen = function(action, id) {
    if (id) {
      action = hsUrlBindParam(action, _this.idVar, id);
    }
    if (_this.useFW) {
      _this.getFW();
      _this.FW.setContent(action, true, true);

      _this.FW.onLoad = function() {
        if (_this.FW.innerWindow.FA) {
          _this.FA = _this.FW.innerWindow.FA;
          _this.FA.useFW = true;
          _this.FA.autoClose = true;
          _this.FA.onBack = _this.onBack;
          _this.FA.onFail = _this.onFail;
        }
      }

      var ops = _this.openParams;
      for (var i = 0; i < 3; i ++) {
        if (!ops[i]) {
          ops[i] = null;
        }
      }

      switch (_this.openType) {
        case 0: _this.FW.open(ops[0], ops[1], ops[2]); break;
        case 1: _this.FW.openOnUserPos(ops[0], ops[1], ops[2]); break;
        case 1: _this.FW.openOnMousePos(ops[0], ops[1]); break;
      }
    }
    else {
      location.href = action;
    }
  };

  _this.actionSubmit = function(action, send) {
    var fl = new HsTW.HsFloatLoading(self.connectingMsg);
    fl.start();

    var rsp = hsAjaxRequestPost(action, send);
    var rst = hsAjaxRequestResult(rsp);

    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/chrome\/([\d.]+)/) != null){
        setTimeout('var fl = new HsTW.HsFloatLoading();fl.stop();fl = null;', 1000);
    }else{
        fl.stop();
    }

    fl = null;

    _this.actionBack(rst);
  };

  _this.actionBack = function(rst) {
    if (rst == null) {
      return;
    }

    if (rst.__result) {
      if (!_this.onBack()) {
        location.reload();
      }
    }
    else {
      _this.onFail();
    }
  };

  /** 常规动作伪事件 **/

  _this.onGet = function(id) {
    return false;
  };

  _this.onSet = function(id) {
    return false;
  };

  _this.onDel = function(id) {
    return false;
  };

  _this.onDel2 = function(id) {
    return false;
  };

  _this.onBack = function() {
    return false;
  };

  _this.onFail = function() {
  }

  /** 列表常规事件 **/

  _this.initEvent = function() {
    _this.lightReg = eval("/ ?"+_this.lightClass+"/");
    _this.hoverReg = eval("/ ?"+_this.hoverClass+"/");

    _this.checkBoxes = [];

    var n = 0;
    var tb = hsFirstElement(_this.listObj);

    TR:for (var i = 0; i < tb.childNodes.length; i ++) {
      var tr = tb.childNodes[i];
      if (tr.nodeType != 1 || tr == null) {
        continue;
      }

      if (i % 2 == 0) {
        tr.className = _this.lightClass;
      }

      TD:for (var j = 0; j < tr.childNodes.length; j ++) {
        var td = tr.childNodes[j];
        if (td.nodeType != 1 || td == null) {
          continue;
        }

        if (td.tagName == "TH") {
          continue TR;
        }

        /** 鼠标悬浮高亮 **/

        if (HsBI.name == "MSIE" && HsBI.version < 7) {
          var ev = new HsEventListener(td, "mouseout", _this.hout);
          ev.n = n;

          new HsEventListener(td, "mouseover", _this.hover);
        }

        /** 鼠标点击锁定 **/

        if (!_this.noClick && !td.getAttribute("no_click") && !td.onclick) {
          var ev = new HsEventListener(td, "click", _this.click);
          ev.n = n;

          _this.setCk(n, j, tr, td);
        }

        /** 文本浮动显示 **/

        if (!_this.noTitle && !td.getAttribute("no_title") && !td.title) {
          var tt = td.innerHTML;

          tt = tt.replace(/<.+?>/gm, " ");
          tt = tt.replace(/[\t\r\n]/gm, " ");
          tt = tt.replace(/ {2,}/gm, " ");
          tt = tt.trim();
          tt = hsHtmlDecode(tt);

          if (tt) {
            td.title = tt;
          }
        }
      }

      n ++;
    }
  };

  _this.hover = function(e) {
    var tr = _this.getTr(e.target);

    if (tr.className) {
      if (!_this.hoverReg.test(tr.className)) {
        tr.className += " "+_this.hoverClass;
      }
    }
    else {
      tr.className = _this.hoverClass;
    }
  };

  _this.hout = function(e, he) {
    var tr = _this.getTr(e.target);

    if (!_this.noClick) {
      var ck = _this.checkBoxes[he.n];
      if (ck && ck.checked) {
        return;
      }
    }

    if (tr.className) {
      tr.className = tr.className.replace(_this.hoverReg, "");
    }
  };

  _this.click = function(e, he) {
    var ck = _this.checkBoxes[he.n];

    // 跳过链接,下拉列表,文本区域
    if (e.target.tagName == "A"
    || e.target.tagName == "SELECT"
    || e.target.tagName == "TEXTAREA") {
      return false;
    }

    // 跳过按钮等(不跳过定位checkbox)
    if (e.target.tagName == "INPUT"
    && e.target != ck) {
      return false;
    }

    // 缺少定位checkbox
    if (!ck) {
      hsError(self.listActionNoCheckBoxErr, "HsListEvent");
      return false;
    }

    // 更改选择框状态
    if (ck != e.target && !ck.disabled) {
      ck.checked = ck.checked ? false : true;
    }

    var tr = ck.parentNode.parentNode;

    // 更改行样式
    if (ck.checked) {
      if (tr.className) {
        if (!_this.hoverReg.test(tr.className)) {
          tr.className += " "+_this.hoverClass;
        }
      }
      else {
        tr.className = _this.hoverClass;
      }
    }
    else {
      tr.className = tr.className.replace(_this.hoverReg, "");
    }

    // 响应选择框事件
    if (ck != e.target && !ck.disabled && ck.onclick) {
      ck.onclick();
    }

    return true;
  };

  _this.checkOne = function(ck, checked, onclick) {
    // 获取对象
    if (typeof(ck) != "object") {
      ck = _this.getCkById(ck);
    }

    // 如果被禁用则不让修改状态
    if (ck.disabled) {
      return false;
    }

    // 更改状态
    if (typeof(checked) == "object") {
      ck.checked = checked.checked;
    }
    else {
      ck.checked = checked;
    }

    var tr = ck.parentNode.parentNode;

    // 更改行样式
    if (ck.checked) {
      if (tr.className) {
        if (!_this.hoverReg.test(tr.className)) {
          tr.className += " "+_this.hoverClass;
        }
      }
      else {
        tr.className = _this.hoverClass;
      }
    }
    else {
      tr.className = tr.className.replace(_this.hoverReg, "");
    }

    // 响应事件
    if (onclick) {
      if (typeof(onclick) == 'function') {
        onclick(ck);
      }
    }
    else if (ck.onclick) {
      ck.onclick();
    }

    return true;
  };
  _this.checkAll = function(checked, onclick) {
    if (typeof(checked) == "undefined") {
      checked = _this.checked = !_this.checked;
    }

    for (var i = 0; i < _this.checkBoxes.length; i ++) {
      var ck = _this.checkBoxes[i];
      _this.checkOne(ck, checked, onclick);
    }
  };

  _this.getTr = function(node) {
    var i = 0;
    while (true) {
      node = node.parentNode;
      if (node.tagName == "TR") {
        return node;
      }
      if (i > 10) {
        return null;
      }
      i ++;
    }
  };

  _this.getCkByLn = function(ln) {
    return _this.checkBoxes[ln];
  };

  _this.getCkById = function(id) {
    for (var i = 0; i < _this.checkBoxes.length; i ++) {
      if (_this.checkBoxes[i].value = id) {
        return _this.checkBoxes[i];
      }
    }
    return null;
  };

  _this.setCk = function(n, j, tr, td) {
    if (_this.checkBoxes[n]) {
      return;
    }

    var ck = hsFirstElement(td);

    // 已经是最后一个格了
    //if (tr.childNodes.length == j + 1) {
      // 但还是没有找到checkbox
      if (!ck || (ck.tagName != "INPUT" && ck.type.toUpperCase() != "CHECKBOX")) {
        // 则自行创建一个checkbox
        ck = document.createElement("input");
        ck.type = "checkbox";
        ck.style.width = "0px";
        ck.style.height = "0px";
        ck.style.overflow = "hidden";
        ck.style.visibility = "hidden";
        ck.style.position   = "absolute";
        td.appendChild(ck);
      }
//}

    if (ck) {
      // 如果被选中了而行没有高亮
      if (ck.checked && !_this.hoverReg.test(tr.className)) {
        // 则将行样式设为高亮
        if (tr.className) {
          tr.className += " "+_this.hoverClass;
        }
        else {
          tr.className = _this.hoverClass;
        }
      }
      _this.checkBoxes[n] = ck;
    }
  };

  /** 对象初始化 **/

  _this.init();
}

/**
 * 复选框全选操作
 *
 * @author HuangHong
 */
function hsCheckAll(checkname, checked, onclick) {
  if (typeof(checked) == "undefined" || checked === null) {
    checked = self.hsChecked = !self.hsChecked;
  }
  else if (typeof(checked) == "object") {
    checked = checked.checked;
  }

  var checkboxes;
  if (typeof(checkname) == "object") {
    checkboxes = checkname;
  }
  else {
    checkboxes = hsName(checkname);
  }

  for (var i = 0; i < checkboxes.length; i ++) {
    var ck = checkboxes[i];
    ck.checked = checked;

    if (onclick) {
      if (typeof(onclick) == "function") {
        onclick(ck);
      }
    }
    else if (ck.onclick) {
      ck.onclick();
    }
  }
}

/**
 * 复选框选中数量
 *
 * @author HuangHong
 */
function hsCheckedNum(checkname) {
  var checkboxes;
  if (typeof(checkname) == "object") {
    checkboxes = checkname;
  }
  else {
    checkboxes = hsName(checkname);
  }

  var num = 0;
  for (var i = 0; i < checkboxes.length; i ++) {
    if (checkboxes[i].checked) {
      num ++;
    }
  }

  return num;
}
